package com.atguigu.demo2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 * @date 2021/8/8
 */
public class Work1 {
    public static void main(String[] args) {
        Resource resource = new Resource();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                resource.abc();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                resource.one23();
            }
        }, "B").start();
    }
}

class Resource {
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    String s = "";


    public void abc() {
        lock.lock();
        try {
            // 判断
            while ("abc".equals(s)) {
                condition.await();
            }
            // 工作
            s = "abc";
            System.out.println(Thread.currentThread().getName() + "----" + s);
            // 通知
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void one23() {
        lock.lock();
        try {
            // 判断
            while ("123".equals(s)) {
                condition.await();
            }
            // 工作
            s = "123";
            System.out.println(Thread.currentThread().getName() + "----" + s);
            // 通知
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


}
